/**
* @description: 待办工单 => 执行工单
* @author: oahcoay
* @date:
**/
<template>
  <div class="perform-task-main">
    <nav-bar class="header" back title="执行工单" @goBack="goBack"/>
    <view class="main-container">
      <plateTitle title="工单详情" class="plate-title"/>
      <view class="task-info-container">
        <van-cell-group>
          <van-cell v-for="(item,index) in taskInfoData" :key="index" :title="item.title" :value="item.value" />
        </van-cell-group>
      </view>
      <plateTitle title="工单执行" class="plate-title"/>


      <view v-for="(item, index) in executeData" :key="index">
        <van-row type="flex" justify="space-between" class="item-title mb20">
          <van-col span="12"><span style="font-size: 14px; color: #ee0a24" v-if="index<2">*</span>{{item.executeName}}</van-col>
          <van-col span="6" style="text-align: right;">
            <img class="small-img-btn" src="../../static/img/ywadd.png" @click="handleAdd(index)" alt="" />
          </van-col>
        </van-row>
        
        <div class="work-content" v-for="(v, i) in item.executionTerm" :key="i">
          <!-- 执行照片 -->
          <view class="info-container"  v-show="v.executionFileEntity">
            <van-row type="flex" justify="space-between" class="mb20">
          

              <van-col span="6">现场照片</van-col>
              <van-col span="6" style="text-align: right;">
             		<img class="small-img-btn" src="../../static/img/delete.png" @click="handleDel(v.objId, [index,i])" alt=""/>
              </van-col>
            </van-row>
            <div class="image-wrap">
              <div class="image-list" >
                <!-- {{v.executionFileEntity[0]}} -->
                
                <div
                  class="upload-button"
                  v-for="(imgItem, imgIndex) in v.executionFileEntity"
                  :key="imgIndex"
                  :style="{'background-image': `url(${bgImg})`}"
                  
                >
                
                  <div v-if="imgItem.img" class="delete-icon" @click.stop="imageHandle(imgItem, imgIndex, 'DELETE', [index, i, imgIndex])">×</div>
                  <img v-if="imgItem.img" :src="imgItem.img" alt="" @click.stop="imageHandle(imgItem, imgIndex, 'PREVIEW', [index, i, imgIndex])">
                </div>
                <img v-if="v.executionFileEntity.length < wxCount" :src="bgImg" alt="" class="addImg-btn"
									@click.stop="imageHandle('', '', 'CHOOSE', [index, i])">
              </div>
            </div>

            <van-divider dashed/>
            <!-- 备注 -->
            <view class="mb20">备注</view>
            <div class="remark-wrap">
              <textarea class="remark-text" v-model="v.notes" :placeholder="placeholders[index]">
              </textarea>
            </div>

          </view>

        </div>

      </view>
    
     
      
    </view>
    <footer>
      <van-button  @click="goSave">保存</van-button>
      <van-button type="primary" @click="goSubmit" >提交</van-button>
    </footer>

  

    <van-popup class="van-preview-wrap" v-model="showPreview" @click="showPreview = false">
      <van-swipe v-if="currentImgIndex.length>0&&executeData[currentImgIndex[0]].executionTerm.length!=0">
        <div v-for="(image, index) in executeData[currentImgIndex[0]].executionTerm[currentImgIndex[1]].executionFileEntity" :key="index">
          <van-swipe-item v-if="image.img" style="text-align: center;">
            <!-- <div style="width: 100%; text-align: center;">{{ image.previewName }}</div> -->
            <img :src="image.img" />
          </van-swipe-item>
        </div>
      </van-swipe>
    </van-popup>
  </div>
</template>
<script>
import config from "../../common/config";
import wx from '../../static/common_js/jweixin_1.0.0'

import navBar from "../../components/common/nav-bar";
import plateTitle from '../../components/business/plateTitle.vue';
import { debounce } from '../../utils'

import moment from "moment";
import axios from "axios";
import {Dialog, Toast} from "vant";
import {mapGetters} from "vuex";
import { merge } from "lodash";




const fileTemplate = [
  {
    name: "OTHER.jpg",
    // previewName: "其他照片",
    // type: "OTHER",
    raw: null, // raw文件
    img: '', // 用来显示的照片
  },
];
export default {
  name: "performTask",
  components: {navBar, plateTitle},
  props: {},
  data() {
    return {
      baseUrl: '', // 基础url
      taskName: '',
      siteName: '',
      // tmsTim: '',
      startTime: '',
      endTime: '',
      curObjId: '',
      // executionClass: [],
      placeholders:[
        '示例：220kV龙祥线引下光缆封堵A/B/C',
        '示例：220kV龙祥线引下光缆三点接地',
        '示例：华为SDH设备风扇故障， 更换设备风扇',
        '示例：GPT设备',
        '示例：通信机房精密空调'
      ],
      files: fileTemplate, // 照片map
      executeData: [
        {
          executeName: '封堵',
          isRequired: true,
          executionTerm: [
            {
              executionFileEntity: [],
              notes: '',
            }
          ]
        },
        {
          executeName: '光缆',
          isRequired: false,
          executionTerm: [
            {
              executionFileEntity: [],
              notes: '',
            }
          ]
        },
        {
          executeName: '遗留隐患处置',
          isRequired: false,
          executionTerm: [
            {
              executionFileEntity: [],
              notes: '',
            }
          ]
        },
        {
          executeName: '通信设备',
          isRequired: false,
          executionTerm: [
            {
              executionFileEntity: [],
              notes: '',
            }
          ]
        },
        {
          executeName: '动环设备',
          isRequired: false,
          executionTerm: [
            {
              executionFileEntity: [],
              notes: '',
            }
          ]
        },
      ],
      delList: [], // 被删除的列表，需要和后台交互
      showPreview: false,
      wxCount: 6, //相册可选取数量，默认6张
      base64List: [], //相册文件数据

      currentImgIndex: [],
      bgImg: require("../../static/img/bg_qita.png"),
			imgBase64: ''

    };
  },
  computed: {
    ...mapGetters(["userData"]),
    taskInfoData:function() {
      return [
        {
          title: "工单名称",
          value:  this.taskName
        },
        {
          title: "巡视站点",
          value: this.siteName
        },
        {
          title: "计划开始时间",
          value: this.startTime
        },
        {
          title: "计划结束时间",
          value: this.endTime
        },
      ]
    }
  },
  watch: {},
  mounted() {
  
  },
  onLoad(options) {
    config.getOptions.then(res => {
      this.baseUrl = res.firstUrl;
      // this.baseUrl ='http://192.168.124.93:18001';
    })
    this.curObjId = options.objId
    this.$apiRequest.qjqcApi.getAutumnInspectionTaskDetailsInfo({objId: options.objId, inletType: options.inletType}).then(res => {
      console.log('xxxxx', res.data)
      this.taskName = res.data.name
      this.siteName = res.data.taskSiteName
      this.startTime = res.data.tmsStartTim?moment(res.data.tmsStartTim).format("YYYY-MM-DD HH:mm"):null
      this.endTime = res.data.tmsEndTim? moment(res.data.tmsEndTim).format("YYYY-MM-DD HH:mm"):null
      //  this.tmsTim =  startTime+'~'+endTime

      this.executeData = JSON.parse(JSON.stringify(res.data.executionClass))
      this.executeData.forEach((item, index, arr)=>{
        if (item.executionTerm.length==0){
          arr[index].executionTerm.push({
            executionFileEntity: [],
            notes: '',
          })
        }
        item.executionTerm.forEach((item1, index1)=>{
         
          item1.executionFileEntity.forEach((item2, index2, arr2)=>{
            if (item2.furl) {
              arr2[index2] = Object.assign({},item2, {
                img: this.baseUrl + item2.furl,
                raw: null,
                name: item2.wjmc,
              })
            }
           
          })
          
          // if (item1.executionFileEntity.length < 6) {  // 最多上传6张 不够添加空对象
          //   item1.executionFileEntity.push({
          //     img: '',
          //     raw: null,
          //     name: '',
          //   })
          // }
          
        })
      })
      // this.executeData = res.date.executionClass
    });
  },
  // 组件销毁后清空填写内容（将填写内容初始化为空）
  beforeDestroy() {
  },
  methods: {
    goSave: debounce(function(){
      // if (!this.verifyFormData()){
      //   return
      // }
      this.handleSubmit(0)
    }, 1200),
    goSubmit: debounce(function(){
      if (!this.verifyFormData()){
        return
      }
      Dialog.confirm({
        title: '是否确认提交？',
        message: '注：提交后不可再次编辑，请确认提交内容',
        confirmButtonColor: "#417adc"
      }).then(() => {
        this.handleSubmit(1)
      })
    }, 1200),
    verifyFormData(){
      // 必填校验
      // 封堵
      if(this.executeData[0].executionTerm.length > 0) {
        if (this.executeData[0].executionTerm[0].executionFileEntity.length==0){
          Toast.fail('请完善必填内容')
          return false
        }
        if (!this.executeData[0].executionTerm[0].notes){
          Toast.fail('请完善必填内容')
          return false
        }
      } else {
        Toast.fail('请完善必填内容')
        return false
      }
      
      // 光缆
      if (this.executeData[1].executionTerm.length > 0){
        if (this.executeData[1].executionTerm[0].executionFileEntity.length==0){
          Toast.fail('请完善必填内容')
          return false
        }
        if (!this.executeData[1].executionTerm[0].notes){
          Toast.fail('请完善必填内容')
          return false
        }
      } else {
        Toast.fail('请完善必填内容')
        return false
      }
      
      return true
    },
    handleSubmit(type){
      Toast.loading({
        duration: 0,
        message: '加载中...',
        forbidClick: true
      })
      var formData = new FormData()
      formData.append(`userId`, this.userData.userId )
      formData.append(`submitType`, type)  // 提交类型 （0：暂存，1：提交）
      formData.append(`taskId`,  this.curObjId )
      this.executeData.forEach((item, index)=>{
        item.executionTerm.forEach((item1, index1)=>{
          if (item1.notes||item1.executionFileEntity.length>0) {
            item1.notes&&formData.append(`executionClassEntity[${index}].executionTerm[${index1}].notes`, item1.notes )
            formData.append(`executionClassEntity[${index}].executionTerm[${index1}].executeType`, item.code)
            item1.objId&&formData.append(`executionClassEntity[${index}].executionTerm[${index1}].objId`, item1.objId)
            item1.executionFileEntity.forEach((item2, index2, arr2)=>{
              if (item2.img) {
                if (item2.raw) {
                  formData.append(`executionClassEntity[${index}].executionTerm[${index1}].executionFileEntity[${index2}].file`, item2.raw)
                } else {
                  formData.append(`executionClassEntity[${index}].executionTerm[${index1}].executionFileEntity[${index2}].objId`, item2.objId)
                }
              }
            })
          }
         
        })
      })

      let config = {
        headers: {
          'Content-Type': 'multipart/form-data',
          Authorization: uni.getStorageSync('token') || ''
        }
      }
      let url = ''
      // #ifndef IGW
      url = '/ap/txksh/kosinManage/rest/api/autumn/submitAutumTaskInfo'
      // #endif
    // #ifdef IGW
    url = `${this.baseUrl}/txksh/kosinManage/rest/api/autumn/submitAutumTaskInfo`
    // url = `http://10.0.1.18:18001/txksh/kosinManage/rest/api/autumn/submitAutumTaskInfo`
    // #endif
      // url = `http://192.168.124.93:18001/txksh/kosinManage/rest/api/autumn/submitAutumTaskInfo`

      axios.post(url, formData, config).then(res => {
        Toast.clear()
        if (res.data.code == 0) {
          if (type==0) {
            Dialog.alert({
              message: '保存成功',
              theme: 'round-button',
            });
          } else {
            Toast('提交成功')
          }
          uni.navigateTo({
            url: `/pages/autumnInspection/taskList/index`
          })
        } else {
          Toast.clear()
          Toast(res.data.msg)
        }
      })
    
    },
    handleAdd(index){
      
      this.executeData[index].executionTerm.push({
        executionFileEntity: [],
        notes: '',
      }) 
    },
    handleDel(id, idxArr){
      Dialog.confirm({
        title: '警告',
        message: '是否确认删除该执行项？',
        confirmButtonColor: "#417adc"
      }).then(() => {
        if (id) {
          this.$apiRequest.qjqcApi.deleteExecutionItem({objId: id}).then(res=>{
            if (res.code == 0){
              this.executeData[idxArr[0]].executionTerm.splice(idxArr[1], 1);
              Toast('删除成功！')
            } else {
              Toast.clear()
              Toast(res.msg)
            }
          })
        } else {
          this.executeData[idxArr[0]].executionTerm.splice(idxArr[1], 1);
          Toast('删除成功！')
        }
      })
    },
    goBack() {
      // 返回待办列表
      uni.navigateTo({
        url: "/pages/autumnInspection/taskList/index"
      });
    },
   
    imageHandle (imgItem, imgIndex, handleType, i) {
      this.currentImgIndex = i

      if (handleType === 'CHOOSE') {
        this.choosePhoto();
      } else if (handleType === 'PREVIEW') {
        this.showPreview = true;
      } else if (handleType === 'DELETE') {
        Dialog.confirm({
          message: `是否确认删除该照片`
        })
          .then(() => {
            if(imgItem.objId) {
              this.$apiRequest.qjqcApi.deleteFileInfo({objId: imgItem.objId}).then(res=>{
                if (res.code == 0){
                  Toast('删除成功！')
                  this.executeData[this.currentImgIndex[0]].executionTerm[this.currentImgIndex[1]].executionFileEntity.splice(this.currentImgIndex[2], 1);
                } else {
                  Toast.clear()
                  Toast(res.msg)
                }
              })
            } else {
              Toast('删除成功！')
              this.executeData[this.currentImgIndex[0]].executionTerm[this.currentImgIndex[1]].executionFileEntity.splice(this.currentImgIndex[2], 1);
            }
            
          })
          .catch(() => {
            // on cancel
          })
      }
    },
    choosePhoto1() {

      const photoName = `${new Date().getTime()}`
      this.executeData[this.currentImgIndex[0]].executionTerm[this.currentImgIndex[1]].executionFileEntity.push({
        img: this.imgBase64,
        raw: this.dataURLtoFile(this.imgBase64,`${photoName}.jpeg`),
      })
      
    },
    choosePhoto() {
      let _this = this
      //相册可选的数量
      let num = 0
      
      _this.executeData[_this.currentImgIndex[0]].executionTerm[_this.currentImgIndex[1]].executionFileEntity.forEach(item => {
        if (item.img) {
          num++
        }
      })
      let selectNum = _this.wxCount - num
      console.log(selectNum, _this.wxCount, num)
      wx.chooseImage({
        count: selectNum,
        sourceType: ['album','camera'],
        success: (chooseImageRes) => {
						_this.syncLocalImg(chooseImageRes.localIds)

          // wx.getLocalImgData({
          //   localId: chooseImageRes.localIds[0].toString(),
          //   success: function (res) {
          //       const localData = res.localData;
          //       let imageBase64 = '';
          //       if (localData.indexOf('data:image') == 0) {
          //           //苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
          //           imageBase64 = localData;
          //       } else {
          //           //此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
          //           //此时一个正常的base64图片路径就完美生成赋值到img的src中了
          //           imageBase64 = 'data:image/jpeg;base64,' + localData.replace(/\n/g, '');
          //       }
                
          //       // _this.$set(_this.files, imgIndex, merge(_this.files[imgIndex], {
          //       //    raw: _this.h5_url_to_blob(imageBase64),
          //       //    img: imageBase64
          //       // }));


          //       merge(_this.executeData[_this.currentImgIndex[0]].executionTerm[_this.currentImgIndex[1]].executionFileEntity[_this.currentImgIndex[2]], {
          //         img: imageBase64,
          //         raw: _this.h5_url_to_blob(imageBase64),
          //       })

          //       let listArr = _this.executeData[_this.currentImgIndex[0]].executionTerm[_this.currentImgIndex[1]].executionFileEntity
          //       if (listArr.length < 6&& listArr[listArr.length-1].img) {  // 最多上传9张 不够添加空对象
          //         _this.executeData[_this.currentImgIndex[0]].executionTerm[_this.currentImgIndex[1]].executionFileEntity.push({
          //           img: '',
          //           raw: null,
          //           name: '',
          //         })
          //       }

                
                
          //   }
          // });
       
       },
        fail: (error) => {
          console.log(error);
        }
      });
    },
    h5_url_to_blob(url) {
      let arr = url.split(',');
      let mime = arr[0].match(/:(.*?);/)[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], { type: mime });
    },
    async syncLocalImg(localIds) {
				this.base64List = []
				console.log("localIds", localIds)
				for (let i = 0; i < localIds.length; i++) {
					await this.syncUpload(localIds[i], i, localIds.length)
				}
    },
    syncUpload(localId, i, localIdsLength) {
				let _this = this;
				console.log("localId", localId)
				return new Promise(resolve => {
					wx.getLocalImgData({
						localId, // 图片的localID
						success: function(resBackData) {
							let localData = resBackData.localData;
							let imageBase64 = ''
							const photoName = `${new Date().getTime()}`
							//判断是否有这样的头部
							if (localData.indexOf('data:image') == 0) {
								//苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
								imageBase64 = localData
							} else {
								//此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
								//此时一个正常的base64图片路径就完美生成赋值到img的src中了
								imageBase64 =
									'data:image/jpeg;base64,' + localData.replace(/\n/g, '')
							}
							//直接使用imageBase64展示，会导致swipe卡顿
							let file = _this.dataURLtoFile(imageBase64,
								`${photoName}.jpeg`)
							let blob = _this.h5_url_to_blob(imageBase64)
							_this.base64List.push({
								raw: file,
								img: URL.createObjectURL(blob),
							})
							if (i + 1 === localIdsLength) {
								_this.base64List.forEach(img => {
								// 	_this.surveyArr[_this.surveyIndex].file.push(img)
                  _this.executeData[_this.currentImgIndex[0]].executionTerm[_this.currentImgIndex[1]].executionFileEntity.push(img)
								})
							}
							resolve("ok")
						}
					})
				})
		},
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], filename, { type: mime })
    },
  }
};
</script>
<style scoped lang="scss">
.perform-task-main {
  width: 100vw;
  height: 100vh;
  background: #F2F6FA;
  overflow: hidden;

  .van-preview-wrap {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    .van-swipe {
      width: 100%;
      height: 60%;
    }
    img {
      height: 90%;
    }
  }
  
  .main-container {
    height: calc(100vh - #{px2vh(400)});
    padding: px2vh(30) px2vw(30) px2vh(30) px2vw(30);
    overflow: auto;
    .small-img-btn {
      width: px2vw(60);
    }
    .item-title{
      color: #666666;
    }
    .mb20 {
      margin-bottom: px2vh(20);
    }
    .work-content {
      // height: 60vh;
      margin-bottom: px2vh(30);
    }
    
    .plate-title {
      margin-top: px2vh(30);
      margin-bottom: px2vh(27);
    }
    
    .info-container {
      padding: px2vh(70) px2vw(50);
      font-size: px2vw(42);
      color: #666666;
      border-radius: $border-radius-base;
      overflow: hidden;
      background-color: #FFFFFF;
      
      /deep/ .van-radio {
        margin-right: px2vw(139.5)
      }
      
      .image-list {
        width: 100%;
        display: flex;
        flex-wrap: wrap;
        .upload-button {
          width: px2vw(230);
          height: px2vw(230);
          flex-shrink: 0;
          background-size: 100% px2vw(230);
          margin: 0 calc((100% - #{px2vw(690)}) / 6) px2vh(60);
          position: relative;
          .delete-icon {
            position: absolute;
            top: px2vw(-20);
            right: px2vw(-20);
            width: px2vw(40);
            height: px2vw(40);
            background-color: rgba(0, 0, 0, 0.7);
            border-radius: 50%;
            color: #fff;
            display: flex;
            justify-content: center;
            align-items: center;
          }
          img {
            width: px2vw(230);
            height: px2vw(230);
            border-radius: px2vw(6);
          }
        }
        .addImg-btn {
          width: px2vw(230);
          height: px2vw(230);
          border-radius: px2vw(6);   
          background-size: 100% px2vw(230);
          margin: 0 calc((100% - #{px2vw(690)}) / 6) px2vh(60);
        }
      }

      .remark-wrap {
        background-color: #FAFAFA;
        padding: px2vh(41) px2vw(56) px2vh(77) px2vw(55);
        border-radius: px2vw(20);
        
        .remark-text {
          height: px2vh(150);
        }
      }

    }
  }
  footer {
    // width: calc(100vw - #{px2vw(60)});
    display: flex;
    .van-button {
      flex: 1;
      margin: px2vh(40) px2vw(40);
      height: px2vh(100);
      color: #fff;
      background-color: #417ADC;
      border: 1px solid #417ADC;
      border-radius: px2vh(60);
    }
  }
  
}
 
</style>